import { isValidJson } from "@/lib/utils";
import { ColumnFilter, ColumnSort } from "@tanstack/react-table";
import { useCallback } from "react";
import { useSearchParams } from "react-router-dom";

export type TableUrlSearchParamsT = {
  pageIndex: number;
  pageSize: number;
  search?: string;
  sorting: ColumnSort[];
  columnFilters: ColumnFilter[];
};

export const useTableUrlSearchParams = () => {
  const [searchParams, setSearchParams] = useSearchParams();

  const pageIndex = searchParams.get("pageIndex")
    ? (parseInt(
        searchParams.get("pageIndex")!
      ) as TableUrlSearchParamsT["pageIndex"])
    : 0;
  const pageSize = searchParams.get("pageSize")
    ? (parseInt(
        searchParams.get("pageSize")!
      ) as TableUrlSearchParamsT["pageSize"])
    : 10;
  const search = searchParams.get("search")
    ? (searchParams.get("search") as TableUrlSearchParamsT["search"])
    : undefined;
  const sorting =
    searchParams.get("sorting") && isValidJson(searchParams.get("sorting")!)
      ? (JSON.parse(
          searchParams.get("sorting")!
        ) as TableUrlSearchParamsT["sorting"])
      : [];
  const columnFilters =
    searchParams.get("columnFilters") &&
    isValidJson(searchParams.get("columnFilters")!)
      ? (JSON.parse(
          searchParams.get("columnFilters")!
        ) as TableUrlSearchParamsT["columnFilters"])
      : [];

  const setTableUrlSearchParams = useCallback(
    (params: Partial<TableUrlSearchParamsT>) => {
      setSearchParams((values: URLSearchParams) => {
        if (params.pageIndex !== undefined) {
          values.set("pageIndex", params.pageIndex.toString());
        }
        if (params.pageSize !== undefined) {
          values.set("pageSize", params.pageSize.toString());
        }
        if (params.search !== undefined) {
          values.set("search", params.search);
        }
        if (params.sorting !== undefined) {
          values.set("sorting", JSON.stringify(params.sorting));
        }
        if (params.columnFilters !== undefined) {
          values.set("columnFilters", JSON.stringify(params.columnFilters));
        }
        return values;
      });
    },
    [pageIndex, pageSize, search, sorting, columnFilters]
  );

  return {
    pageIndex,
    pageSize,
    search,
    sorting,
    columnFilters,
    setTableUrlSearchParams,
  };
};
